/**
 * @file WiFiManager.cpp
 * @brief WiFi连接管理类实现
 */

#include "WiFiManager.h"

// 定义全局实例指针用于静态回调函数
WiFiManager* WiFiManager::instance = nullptr;

WiFiManager::WiFiManager() : server(80) {
    instance = this;
    isConnected = false;
    inConfigMode = false;
    isConnecting = false;
    serverRunning = false;
    
    // 初始化非阻塞重连变量
    lastReconnectAttempt = 0;
    reconnectInterval = 5000; // 5秒重连间隔
    reconnectInProgress = false;
    reconnectAttempts = 0;
    maxReconnectAttempts = 10; // 最多尝试10次
}

void WiFiManager::startReconnect() {
    if (reconnectInProgress || inConfigMode) {
        return;
    }
    
    Serial.println("Starting non-blocking WiFi reconnection...");
    
    // 加载保存的WiFi凭证
    if (loadWiFiCredentials(reconnectSSID, reconnectPassword)) {
        reconnectInProgress = true;
        reconnectAttempts = 0;
        lastReconnectAttempt = 0; // 立即开始第一次尝试
        
        Serial.print("Attempting to reconnect to: ");
        Serial.println(reconnectSSID);
        
        if (displayCallback) {
            displayCallback("Reconnecting to", reconnectSSID, "Please wait...");
        }
    } else {
        Serial.println("No saved WiFi credentials available for reconnection");
    }
}

void WiFiManager::updateReconnect() {
    if (!reconnectInProgress) {
        return;
    }
    
    unsigned long currentMillis = millis();
    
    // 检查是否需要尝试重连
    if (currentMillis - lastReconnectAttempt >= reconnectInterval) {
        lastReconnectAttempt = currentMillis;
        reconnectAttempts++;
        
        Serial.print("WiFi reconnection attempt ");
        Serial.print(reconnectAttempts);
        Serial.print("/");
        Serial.println(maxReconnectAttempts);
        
        // 设置WiFi模式为STA
        WiFi.mode(WIFI_STA);
        
        // 开始连接（非阻塞）
        WiFi.begin(reconnectSSID.c_str(), reconnectPassword.c_str());
        
        // 检查是否超过最大尝试次数
        if (reconnectAttempts >= maxReconnectAttempts) {
            Serial.println("WiFi reconnection failed, reached maximum attempts");
            reconnectInProgress = false;
            
            if (displayCallback) {
                displayCallback("WiFi Reconnect", "Failed", "Max attempts reached");
            }
        }
    }
    
    // 检查连接状态
    if (WiFi.status() == WL_CONNECTED) {
        Serial.println("WiFi reconnected successfully!");
        isConnected = true;
        reconnectInProgress = false;
        
        if (displayCallback) {
            displayCallback("WiFi Reconnected", "IP: " + WiFi.localIP().toString(), "Ready");
        }
    }
}

bool WiFiManager::isReconnecting() {
    return reconnectInProgress;
}

String WiFiManager::generateAPName() {
    uint32_t chipId = 0;
    for(int i = 0; i < 17; i = i + 8) {
        chipId |= ((ESP.getEfuseMac() >> (40 - i)) & 0xff) << i;
    }
    return "ESP32-" + String(chipId, HEX);
}

bool WiFiManager::init() {
    Serial.println("Initializing WiFi manager...");
    
    // 初始化EEPROM
    if (!EEPROM.begin(EEPROM_SIZE)) {
        Serial.println("EEPROM initialization failed!");
        return false;
    }
    
    // 显示启动信息
    if (displayCallback) {
        displayCallback("ESP32 Starting", "Please wait...", "");
    }
    
    // 先设置WiFi模式为STA
    WiFi.mode(WIFI_STA);
    delay(100);
    
    // 尝试连接已保存的WiFi
    String ssid, password;
    if (loadWiFiCredentials(ssid, password)) {
        Serial.print("Attempting to connect to saved WiFi: ");
        Serial.println(ssid);
        
        if (displayCallback) {
            displayCallback("Connecting to", ssid, "Please wait...");
        }
        
        // 尝试连接WiFi
        if (connectToWiFi(ssid, password, 40)) {
            Serial.println("WiFi connected successfully");
            return true;
        } else {
            Serial.println("WiFi connection failed, starting config mode");
            startConfigMode();
            return false;
        }
    } else {
        Serial.println("No saved WiFi credentials found, starting config mode");
        startConfigMode();
        return false;
    }
}

void WiFiManager::handleClient() {
    if (inConfigMode) {
        server.handleClient();
    }
}

bool WiFiManager::isWiFiConnected() {
    return isConnected && (WiFi.status() == WL_CONNECTED);
}

String WiFiManager::getLocalIP() {
    return WiFi.localIP().toString();
}

void WiFiManager::setDisplayCallback(DisplayCallback callback) {
    displayCallback = callback;
}

bool WiFiManager::isInConfigMode() {
    return inConfigMode;
}

String WiFiManager::getAPName() {
    return apSSID;
}

void WiFiManager::printNetworkInfo() {
    Serial.println("=== Network Information ===");
    Serial.print("WiFi mode: ");
    switch (WiFi.getMode()) {
        case WIFI_OFF: Serial.println("WIFI_OFF"); break;
        case WIFI_STA: Serial.println("WIFI_STA"); break;
        case WIFI_AP: Serial.println("WIFI_AP"); break;
        case WIFI_AP_STA: Serial.println("WIFI_AP_STA"); break;
    }
    
    Serial.print("WiFi status: ");
    switch (WiFi.status()) {
        case WL_NO_SHIELD: Serial.println("WL_NO_SHIELD"); break;
        case WL_IDLE_STATUS: Serial.println("WL_IDLE_STATUS"); break;
        case WL_NO_SSID_AVAIL: Serial.println("WL_NO_SSID_AVAIL"); break;
        case WL_SCAN_COMPLETED: Serial.println("WL_SCAN_COMPLETED"); break;
        case WL_CONNECTED: Serial.println("WL_CONNECTED"); break;
        case WL_CONNECT_FAILED: Serial.println("WL_CONNECT_FAILED"); break;
        case WL_CONNECTION_LOST: Serial.println("WL_CONNECTION_LOST"); break;
        case WL_DISCONNECTED: Serial.println("WL_DISCONNECTED"); break;
    }
    
    if (WiFi.status() == WL_CONNECTED) {
        Serial.print("IP address: ");
        Serial.println(WiFi.localIP().toString());
        Serial.print("Signal strength: ");
        Serial.print(WiFi.RSSI());
        Serial.println(" dBm");
    }
    
    Serial.print("Config mode: ");
    Serial.println(inConfigMode ? "Yes" : "No");
    Serial.println("=================");
}

void WiFiManager::forceCloseAP() {
    Serial.println("Forcing AP mode shutdown...");
    
    // 停止服务器
    server.stop();
    serverRunning = false;
    
    // 断开AP
    WiFi.softAPdisconnect(true);
    
    // 设置模式为STA only
    WiFi.mode(WIFI_STA);
    
    inConfigMode = false;
    
    Serial.println("AP mode forced closed");
    printNetworkInfo();
}

void WiFiManager::clearWiFiCredentials() {
    Serial.println("Clearing WiFi credentials...");
    if (!EEPROM.begin(EEPROM_SIZE)) {
        Serial.println("EEPROM initialization failed!");
        return;
    }
    
    // 清空SSID和密码区域
    for (int i = SSID_ADDR; i < SSID_ADDR + 32; i++) {
        EEPROM.write(i, 0);
    }
    for (int i = PASS_ADDR; i < PASS_ADDR + 64; i++) {
        EEPROM.write(i, 0);
    }
    
    if (!EEPROM.commit()) {
        Serial.println("EEPROM commit failed!");
    } else {
        Serial.println("WiFi credentials cleared");
    }
    
    EEPROM.end();
}

void WiFiManager::switchToNormalMode() {
    Serial.println("Switching to normal mode...");
    
    // 停止Web服务器
    server.stop();
    serverRunning = false;
    
    // 关闭AP
    WiFi.softAPdisconnect(true);
    
    // 设置模式为STA only
    WiFi.mode(WIFI_STA);
    
    inConfigMode = false;
    isConnected = true;
    
    Serial.println("Switched to normal mode");
    printNetworkInfo();
    
    // 等待网络稳定
    Serial.println("Waiting for network stabilization...");
    for(int i = 0; i < 10; i++) {
        if (WiFi.status() == WL_CONNECTED && WiFi.localIP()) {
            Serial.println("Network stabilized");
            break;
        }
        delay(1000);
        Serial.print(".");
    }
    
    // 重新启用MQTT（通过外部调用）
    Serial.println("Ready to re-enable MQTT connection...");
    
    if (displayCallback) {
        displayCallback("WiFi Connected", "IP: " + WiFi.localIP().toString(), "Reconnecting MQTT...");
    }
}

bool WiFiManager::startConfigMode() {
    Serial.println("Starting configuration mode");
    
    // 停止当前连接
    WiFi.disconnect();
    delay(1000);
    
    // 设置WiFi模式为AP
    if (!WiFi.mode(WIFI_AP)) {
        Serial.println("Failed to set AP mode");
        return false;
    }
    
    // 生成AP名称
    apSSID = generateAPName();
    
    // 配置AP网络
    IPAddress localIP(192, 168, 4, 1);
    IPAddress gateway(192, 168, 4, 1);
    IPAddress subnet(255, 255, 255, 0);
    
    if (!WiFi.softAPConfig(localIP, gateway, subnet)) {
        Serial.println("AP network configuration failed");
        return false;
    }
    
    // 启动AP
    if (!WiFi.softAP(apSSID.c_str(), "12345678")) {
        Serial.println("AP startup failed");
        return false;
    }
    
    // 等待AP启动
    delay(2000);
    
    // 设置Web服务器路由
    server.on("/", []() {
        if (WiFiManager::instance) {
            WiFiManager::instance->handleRoot();
        }
    });
    
    server.on("/config", HTTP_POST, []() {
        if (WiFiManager::instance) {
            WiFiManager::instance->handleConfig();
        }
    });
    
    server.on("/status", HTTP_GET, []() {
        if (WiFiManager::instance) {
            WiFiManager::instance->handleStatus();
        }
    });

    // 新增扫描路由
    server.on("/scan", HTTP_GET, []() {
        if (WiFiManager::instance) {
            WiFiManager::instance->handleScan();
        }
    });
    
    server.on("/scan-results", HTTP_GET, []() {
        if (WiFiManager::instance) {
            WiFiManager::instance->handleScanResults();
        }
    });
    
    server.onNotFound([]() {
        if (WiFiManager::instance) {
            WiFiManager::instance->handleNotFound();
        }
    });
    
    // 启动服务器
    server.begin();
    serverRunning = true;
    
    inConfigMode = true;
    isConnected = false;
    
    Serial.print("AP created successfully: ");
    Serial.println(apSSID);
    Serial.print("AP IP address: ");
    Serial.println(WiFi.softAPIP());
    
    if (displayCallback) {
        displayCallback("Config Mode", "AP: " + apSSID, "IP: 192.168.4.1");
    }
    
    return true;
}

void WiFiManager::handleRoot() {
        // 从EEPROM加载MQTT配置作为默认值
    String defaultMqttServer, defaultMqttUser, defaultMqttPassword;
    int defaultMqttPort;
    
    // 尝试加载保存的MQTT配置
    bool hasMQTTConfig = loadMQTTCredentials(defaultMqttServer, defaultMqttPort, defaultMqttUser, defaultMqttPassword);
    
    // 如果没有有效的MQTT配置，使用默认值
    if (!hasMQTTConfig) {
        defaultMqttServer = "test.mosquitto.org";
        defaultMqttPort = 1883;
        defaultMqttUser = "";
        defaultMqttPassword = "";
    }
    String html = R"rawliteral(
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ESP32 WiFi配置</title>
    <style>
        body { 
            font-family: 'Microsoft YaHei', Arial, sans-serif; 
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); 
            min-height: 100vh; 
            display: flex; 
            justify-content: center; 
            align-items: center; 
            padding: 20px; 
            margin: 0;
        }
        .container { 
            background: white; 
            border-radius: 20px; 
            box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1); 
            width: 100%; 
            max-width: 500px; 
            overflow: hidden; 
        }
        .header { 
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); 
            color: white; 
            padding: 30px 20px; 
            text-align: center; 
        }
        .header h1 { 
            font-size: 24px; 
            font-weight: 600; 
            margin-bottom: 5px; 
        }
        .content { 
            padding: 30px; 
        }
        .form-group { 
            margin-bottom: 20px; 
        }
        label { 
            display: block; 
            margin-bottom: 8px; 
            font-weight: 500; 
            color: #333; 
            font-size: 14px; 
        }
        input { 
            width: 100%; 
            padding: 15px; 
            border: 2px solid #e1e5e9; 
            border-radius: 10px; 
            font-size: 16px; 
            transition: all 0.3s ease; 
            box-sizing: border-box;
        }
        input:focus {
            border-color: #4facfe;
            outline: none;
        }
        .btn { 
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); 
            color: white; 
            border: none; 
            padding: 15px; 
            border-radius: 10px; 
            font-size: 16px; 
            font-weight: 600; 
            cursor: pointer; 
            width: 100%; 
            transition: transform 0.2s ease, box-shadow 0.2s ease; 
        }
        .btn:hover { 
            transform: translateY(-2px); 
            box-shadow: 0 7px 14px rgba(50, 50, 93, 0.1), 0 3px 6px rgba(0, 0, 0, 0.08); 
        }
        .btn:disabled {
            background: #cccccc;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }
        .status { 
            margin-top: 20px; 
            padding: 15px; 
            border-radius: 10px; 
            text-align: center; 
            font-size: 14px; 
            display: none; 
        }
        .success { 
            background: #d4edda; 
            color: #155724; 
            border: 1px solid #c3e6cb; 
        }
        .error { 
            background: #f8d7da; 
            color: #721c24; 
            border: 1px solid #f5c6cb; 
        }
        .info { 
            background: #d1ecf1; 
            color: #0c5460; 
            border: 1px solid #bee5eb; 
        }
        .loading { 
            display: none; 
            text-align: center; 
            margin: 10px 0; 
        }
        .spinner { 
            border: 3px solid #f3f3f3; 
            border-top: 3px solid #4facfe; 
            border-radius: 50%; 
            width: 20px; 
            height: 20px; 
            animation: spin 1s linear infinite; 
            margin: 0 auto; 
        }
        @keyframes spin { 
            0% { transform: rotate(0deg); } 
            100% { transform: rotate(360deg); } 
        }
        .instructions {
            background: #f8f9fa;
            border-left: 4px solid #4facfe;
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 0 8px 8px 0;
        }
        .instructions h3 {
            margin-top: 0;
            color: #333;
        }
        .instructions ol {
            padding-left: 20px;
            margin-bottom: 0;
        }
        .instructions li {
            margin-bottom: 8px;
        }
        .advanced-toggle {
            background: none;
            border: none;
            color: #4facfe;
            cursor: pointer;
            font-size: 14px;
            margin: 10px 0;
            padding: 5px 0;
            text-align: left;
            width: 100%;
        }
        .advanced-toggle:hover {
            text-decoration: underline;
        }
        .advanced-content {
            display: none;
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            margin: 10px 0;
            border: 1px solid #e1e5e9;
        }
        .port-input {
            width: 100px;
        }
        .form-row {
            display: flex;
            gap: 10px;
            align-items: flex-end;
        }
        .form-row .form-group {
            flex: 1;
            margin-bottom: 0;
        }
        .server-label {
            flex: 2;
        }
        .port-label {
            flex: 1;
        }
        
        /* 网络扫描相关样式 */
        .network-selector {
            position: relative;
        }
        
        .input-with-button {
            display: flex;
            gap: 10px;
        }
        
        .scan-btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 8px;
            padding: 0 15px;
            cursor: pointer;
            white-space: nowrap;
            font-size: 14px;
            transition: all 0.3s ease;
            min-width: 100px;
        }
        
        .scan-btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }
        
        .scan-btn:disabled {
            background: #cccccc;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }
        
        .mini-spinner {
            border: 2px solid #f3f3f3;
            border-top: 2px solid #ffffff;
            border-radius: 50%;
            width: 12px;
            height: 12px;
            animation: spin 1s linear infinite;
            display: inline-block;
            margin-right: 5px;
        }
        
        .network-list-container {
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            background: white;
            border: 1px solid #e1e5e9;
            border-radius: 10px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
            z-index: 1000;
            margin-top: 5px;
            max-height: 300px;
            overflow-y: auto;
        }
        
        .network-list-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px 15px;
            background: #f8f9fa;
            border-bottom: 1px solid #e1e5e9;
            font-weight: 500;
            border-radius: 10px 10px 0 0;
        }
        
        .close-list {
            background: none;
            border: none;
            font-size: 18px;
            cursor: pointer;
            color: #666;
        }
        
        .network-list {
            padding: 5px 0;
        }
        
        .network-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px 15px;
            cursor: pointer;
            border-bottom: 1px solid #f0f0f0;
            transition: background-color 0.2s ease;
        }
        
        .network-item:hover {
            background-color: #f8f9fa;
        }
        
        .network-item:last-child {
            border-bottom: none;
        }
        
        .network-info {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .network-name {
            font-weight: 500;
        }
        
        .network-security {
            font-size: 12px;
            color: #666;
            background: #f0f0f0;
            padding: 2px 6px;
            border-radius: 4px;
        }
        
        .signal-strength {
            display: flex;
            align-items: center;
            gap: 5px;
            font-size: 12px;
            color: #666;
        }
        
        .signal-bars {
            display: flex;
            gap: 1px;
        }
        
        .signal-bar {
            width: 3px;
            height: 8px;
            background: #ddd;
            border-radius: 1px;
        }
        
        .signal-bar.active {
            background: #4CAF50;
        }
        
        .no-networks {
            padding: 20px;
            text-align: center;
            color: #666;
        }

        /* 隐藏网络特殊样式 */
        .hidden-network {
            background-color: #fff3cd !important;
            border-left: 3px solid #ffc107;
        }

        .hidden-network:hover {
            background-color: #ffeaa7 !important;
        }

        .hidden-badge {
            font-size: 10px;
            color: #856404;
            background: #fff3cd;
            padding: 1px 4px;
            border-radius: 3px;
            border: 1px solid #ffeaa7;
        }

        .scan-summary {
            padding: 8px 15px;
            background: #e9ecef;
            font-size: 12px;
            color: #6c757d;
            border-bottom: 1px solid #dee2e6;
        }

        /* 弱信号网络样式 */
        .weak-signal {
            opacity: 0.7;
        }

        .weak-signal .network-name {
            color: #6c757d;
        }

        /* 信号强度颜色 */
        .signal-bar.active.weak {
            background: #ff6b6b;
        }

        .signal-bar.active.fair {
            background: #feca57;
        }

        .signal-bar.active.good {
            background: #4CAF50;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>WiFi配置</h1>
            <p>为您的ESP32设备配置网络连接</p>
        </div>
        
        <div class="content">
            <div class="instructions">
                <h3>配置说明：</h3>
                <ol>
                    <li>点击"扫描网络"按钮发现附近WiFi网络</li>
                    <li>从列表中选择您的WiFi网络</li>
                    <li>输入WiFi密码并点击"连接网络"</li>
                    <li>设备将自动连接并重启</li>
                </ol>
            </div>
            
            <form id="wifi-form">
                <div class="form-group">
                    <label for="ssid">WiFi网络名称 (SSID)</label>
                    <div class="network-selector">
                        <div class="input-with-button">
                            <input type="text" id="ssid" placeholder="请选择或输入WiFi名称" required readonly>
                            <button type="button" class="scan-btn" id="scan-btn" onclick="startNetworkScan()">
                                <span class="btn-text">扫描网络</span>
                                <span class="btn-loading" style="display: none;">
                                    <div class="mini-spinner"></div> 扫描中...
                                </span>
                            </button>
                        </div>
                        
                        <!-- 网络列表容器 -->
                        <div class="network-list-container" id="network-list-container" style="display: none;">
                            <div class="network-list-header">
                                <span>可用网络</span>
                                <button type="button" class="close-list" onclick="closeNetworkList()">×</button>
                            </div>
                            <div class="network-list" id="network-list">
                                <!-- 动态填充的网络列表 -->
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="form-group">
                    <label for="password">WiFi密码</label>
                    <input type="password" id="password" placeholder="请输入您的WiFi密码">
                </div>

                <button type="button" class="advanced-toggle" onclick="toggleAdvanced()">
                    ▶ 高级选项 (MQTT服务器配置)
                </button>
                
                <div class="advanced-content" id="advanced-content">
                    <div class="form-group">
                        <label for="mqtt_server">MQTT服务器地址</label>
                        <input type="text" id="mqtt_server" placeholder="test.mosquitto.org" value=")rawliteral" + defaultMqttServer + R"rawliteral(">
                    </div>
                    
                    <div class="form-row">
                        <div class="form-group server-label">
                            <label for="mqtt_port">MQTT端口</label>
                            <input type="number" id="mqtt_port" class="port-input" placeholder="1883" value=")rawliteral" + String(defaultMqttPort) + R"rawliteral(" min="1" max="65535">
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label for="mqtt_user">MQTT用户名 (可选)</label>
                        <input type="text" id="mqtt_user" placeholder="留空表示无需认证" value=")rawliteral" + defaultMqttUser + R"rawliteral(">
                    </div>
                    
                    <div class="form-group">
                        <label for="mqtt_password">MQTT密码 (可选)</label>
                        <input type="password" id="mqtt_password" placeholder="留空表示无需认证" value=")rawliteral" + defaultMqttPassword + R"rawliteral(">
                    </div>
                    
                    <div style="font-size: 12px; color: #666; margin-top: 10px;">
                        <p><strong>默认配置:</strong> test.mosquitto.org:1883 (无需认证)</p>
                        <p>如果不需要自定义MQTT服务器，请保持默认配置。</p>
                    </div>
                </div>
                
                <div class="loading" id="loading">
                    <div class="spinner"></div>
                    <p>正在连接WiFi，请稍候...</p>
                </div>
                
                <button type="button" class="btn" id="connect-btn" onclick="sendConfig()">连接网络</button>
            </form>
            
            <div class="status" id="status"></div>
        </div>
    </div>

    <script>
        // 网络扫描相关功能
        let scanInterval = null;

        function startNetworkScan() {
            const scanBtn = document.getElementById('scan-btn');
            const btnText = scanBtn.querySelector('.btn-text');
            const btnLoading = scanBtn.querySelector('.btn-loading');
            
            // 显示加载状态
            btnText.style.display = 'none';
            btnLoading.style.display = 'inline';
            scanBtn.disabled = true;
            
            // 清空之前的列表
            document.getElementById('network-list').innerHTML = '';
            document.getElementById('network-list-container').style.display = 'block';
            
            // 开始扫描
            fetch('/scan')
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常: ' + response.status);
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.status === 'scanning') {
                        // 开始轮询扫描结果
                        pollScanResults();
                    } else {
                        throw new Error('扫描启动失败: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Scan start failed:', error);
                    resetScanButton();
                    showStatus('扫描启动失败，请重试', 'error');
                });
        }

        function pollScanResults() {
            if (scanInterval) {
                clearInterval(scanInterval);
            }
            
            scanInterval = setInterval(() => {
                fetch('/scan-results')
                    .then(response => {
                        if (!response.ok) {
                            throw new Error('网络响应不正常: ' + response.status);
                        }
                        return response.json();
                    })
                    .then(data => {
                        if (data.status === 'completed') {
                            clearInterval(scanInterval);
                            displayNetworkList(data.networks);
                            resetScanButton();
                        } else if (data.status === 'error') {
                            clearInterval(scanInterval);
                            resetScanButton();
                            showStatus('网络扫描失败: ' + data.message, 'error');
                        }
                        // 如果状态还是scanning，继续轮询
                    })
                    .catch(error => {
                        console.error('Scan poll failed:', error);
                        clearInterval(scanInterval);
                        resetScanButton();
                        showStatus('扫描结果获取失败', 'error');
                    });
            }, 1000);
        }

        function displayNetworkList(networks) {
            const networkList = document.getElementById('network-list');
            
            if (networks.length === 0) {
                networkList.innerHTML = '<div class="no-networks">未发现可用网络</div>';
                return;
            }
            
            // 按信号强度排序
            networks.sort((a, b) => b.rssi - a.rssi);
            
            let html = '';
            let hiddenNetworks = 0;

            networks.forEach(network => {
                // 统计隐藏网络
                if (network.is_hidden) {
                    hiddenNetworks++;
                }

                const signalLevel = getSignalLevel(network.rssi);
                const securityType = getSecurityType(network.encryption);

                // 特殊处理隐藏网络
                let displayName = network.ssid;
                let networkClass = 'network-item';
                
                if (network.is_hidden) {
                    networkClass += ' hidden-network';
                }
                
                html += `
                    <div class="${networkClass}" onclick="selectNetwork('${displayName.replace(/'/g, "\\'")}')">
                        <div class="network-info">
                            <span class="network-name">${displayName}</span>
                            <span class="network-security">${securityType}</span>
                            ${network.is_hidden ? '<span class="hidden-badge">隐藏</span>' : ''}
                        </div>
                        <div class="signal-strength">
                            <div class="signal-bars">
                                ${getSignalBars(signalLevel)}
                            </div>
                            <span>${network.rssi} dBm</span>
                        </div>
                    </div>
                `;
            });

            // 添加统计信息
            if (hiddenNetworks > 0) {
                html = `<div class="scan-summary">发现 ${networks.length} 个网络 (${hiddenNetworks} 个隐藏网络)</div>` + html;
            } else {
                html = `<div class="scan-summary">发现 ${networks.length} 个网络</div>` + html;
            }
            
            networkList.innerHTML = html;
        }

        function selectNetwork(ssid) {
          // 如果是隐藏网络，需要特殊处理
          if (ssid === '[隐藏网络]') {
              document.getElementById('ssid').removeAttribute('readonly');
              document.getElementById('ssid').placeholder = '请输入隐藏网络的名称';
              document.getElementById('ssid').value = '';
              document.getElementById('ssid').focus();
          } else {
              document.getElementById('ssid').value = ssid;
              document.getElementById('ssid').setAttribute('readonly', 'true');
              document.getElementById('ssid').placeholder = '请选择或输入WiFi名称';
              
              // 自动聚焦到密码输入框
              document.getElementById('password').focus();
          }
          
          closeNetworkList();
        }

        function closeNetworkList() {
            document.getElementById('network-list-container').style.display = 'none';
            resetScanButton();
        }

        function resetScanButton() {
            const scanBtn = document.getElementById('scan-btn');
            const btnText = scanBtn.querySelector('.btn-text');
            const btnLoading = scanBtn.querySelector('.btn-loading');
            
            btnText.style.display = 'inline';
            btnLoading.style.display = 'none';
            scanBtn.disabled = false;
        }

        // 工具函数
        function getSignalLevel(rssi) {
          if (rssi >= -50) return 4; // 优秀
          if (rssi >= -60) return 3; // 良好
          if (rssi >= -70) return 2; // 一般
          if (rssi >= -80) return 1; // 差
          return 0; // 非常差
        }

        function getSignalBars(level) {
          let bars = '';
          for (let i = 0; i < 4; i++) {
              let barClass = 'signal-bar';
              if (i < level) {
                  barClass += ' active';
                  // 根据信号强度设置不同颜色
                  if (level === 1) barClass += ' weak';
                  else if (level === 2) barClass += ' fair';
                  else if (level >= 3) barClass += ' good';
              }
              bars += `<div class="${barClass}"></div>`;
          }
          return bars;
        }

        function getSecurityType(encryption) {
            switch (encryption) {
                case 0: return '开放';
                case 1: return 'WEP';
                case 2: return 'WPA';
                case 3: return 'WPA2';
                case 4: return 'WPA/WPA2';
                case 5: return 'WPA2企业版';
                case 6: return 'WPA3';
                default: return '未知';
            }
        }

        // 原有功能保持不变
        function toggleAdvanced() {
            const content = document.getElementById('advanced-content');
            const toggle = document.querySelector('.advanced-toggle');
            
            if (content.style.display === 'block') {
                content.style.display = 'none';
                toggle.innerHTML = '▶ 高级选项 (MQTT服务器配置)';
            } else {
                content.style.display = 'block';
                toggle.innerHTML = '▼ 高级选项 (MQTT服务器配置)';
            }
        }
        
        function sendConfig() {
            const ssid = document.getElementById('ssid').value;
            const password = document.getElementById('password').value;
            const mqttServer = document.getElementById('mqtt_server').value;
            const mqttPort = document.getElementById('mqtt_port').value;
            const mqttUser = document.getElementById('mqtt_user').value;
            const mqttPassword = document.getElementById('mqtt_password').value;
            
            const statusDiv = document.getElementById('status');
            const loadingDiv = document.getElementById('loading');
            const connectBtn = document.getElementById('connect-btn');
            
            if (!ssid) {
                showStatus('请选择或输入WiFi网络名称', 'error');
                return;
            }
            
            if (!mqttServer) {
                showStatus('请输入MQTT服务器地址', 'error');
                return;
            }
            
            if (!mqttPort || mqttPort < 1 || mqttPort > 65535) {
                showStatus('请输入有效的MQTT端口 (1-65535)', 'error');
                return;
            }
            
            // 显示加载中，禁用按钮
            loadingDiv.style.display = 'block';
            statusDiv.style.display = 'none';
            connectBtn.disabled = true;
            connectBtn.textContent = '连接中...';
            
            // 准备配置数据
            const configData = {
                ssid: ssid,
                password: password,
                mqtt_server: mqttServer,
                mqtt_port: parseInt(mqttPort),
                mqtt_user: mqttUser,
                mqtt_password: mqttPassword
            };
            
            // 发送请求
            fetch('/config', {
                method: 'POST',
                body: JSON.stringify(configData),
                headers: {
                    'Content-Type': 'application/json'
                }
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应不正常: ' + response.status);
                }
                return response.json();
            })
            .then(data => {
                if (data.status === 'success') {
                    showStatus('配置已保存，正在连接WiFi...', 'info');
                    // 开始检查连接状态
                    checkConnectionStatus();
                } else {
                    loadingDiv.style.display = 'none';
                    connectBtn.disabled = false;
                    connectBtn.textContent = '连接网络';
                    showStatus('错误: ' + data.message, 'error');
                }
            })
            .catch(error => {
                loadingDiv.style.display = 'none';
                connectBtn.disabled = false;
                connectBtn.textContent = '连接网络';
                
                console.error('请求错误:', error);
                
                if (error.message.includes('Failed to fetch')) {
                    showStatus('网络连接失败，请检查您是否仍连接到ESP32的WiFi热点', 'error');
                } else {
                    showStatus('网络错误: ' + error.message, 'error');
                }
            });
        }
        
        function checkConnectionStatus() {
            let attempts = 0;
            const maxAttempts = 60; // 最多尝试60次，每次1秒
            
            const checkInterval = setInterval(() => {
                attempts++;
                fetch('/status')
                    .then(response => response.json())
                    .then(data => {
                        if (data.status === 'connected') {
                            showStatus('连接成功! 设备IP地址: ' + data.ip + '<br>配置模式已关闭，设备正在正常工作。', 'success');
                            clearInterval(checkInterval);
                        } else if (attempts >= maxAttempts) {
                            showStatus('连接超时，请检查WiFi密码或信号强度', 'error');
                            clearInterval(checkInterval);
                            document.getElementById('connect-btn').disabled = false;
                            document.getElementById('connect-btn').textContent = '连接网络';
                            document.getElementById('loading').style.display = 'none';
                        } else {
                            document.getElementById('status').innerHTML = `正在尝试连接WiFi... (${attempts}/${maxAttempts})`;
                        }
                    })
                    .catch(() => {
                        // 如果无法访问/status，可能是设备正在切换模式
                        if (attempts >= maxAttempts) {
                            showStatus('连接检查失败，设备可能正在重启或连接失败', 'error');
                            clearInterval(checkInterval);
                            document.getElementById('connect-btn').disabled = false;
                            document.getElementById('connect-btn').textContent = '连接网络';
                            document.getElementById('loading').style.display = 'none';
                        }
                    });
            }, 1000);
        }
        
        function showStatus(message, type) {
            const statusDiv = document.getElementById('status');
            statusDiv.innerHTML = message;
            statusDiv.className = 'status ' + type;
            statusDiv.style.display = 'block';
            
            // 自动滚动到状态消息
            statusDiv.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
        }
        
        // 页面加载完成后自动扫描
        window.onload = function() {
            // 自动开始扫描
            setTimeout(startNetworkScan, 500);
            
            // 原有的回车键支持
            document.getElementById('ssid').addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    document.getElementById('password').focus();
                }
            });
            
            document.getElementById('password').addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    sendConfig();
                }
            });
            
            // 点击页面其他区域关闭网络列表
            document.addEventListener('click', function(e) {
                const networkContainer = document.getElementById('network-list-container');
                const scanBtn = document.getElementById('scan-btn');
                
                if (networkContainer.style.display === 'block' && 
                    !networkContainer.contains(e.target) && 
                    !scanBtn.contains(e.target)) {
                    closeNetworkList();
                }
            });
        }
    </script>
</body>
</html>
)rawliteral";
  
    server.send(200, "text/html", html);
}

void WiFiManager::handleConfig() {
    Serial.println("Received configuration request");
    
    // 添加CORS头
    server.sendHeader("Access-Control-Allow-Origin", "*");
    server.sendHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS");
    server.sendHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    
    // 处理OPTIONS预检请求
    if (server.method() == HTTP_OPTIONS) {
        server.send(200, "text/plain", "");
        return;
    }
    
    if (server.hasArg("plain")) {
        String body = server.arg("plain");
        Serial.print("Received raw data: ");
        Serial.println(body);
        
        // 解析JSON数据
        String ssid = parseJSONValue(body, "ssid");
        String password = parseJSONValue(body, "password");
        String mqttServer = parseJSONValue(body, "mqtt_server");
        String mqttPortStr = parseJSONValue(body, "mqtt_port");
        String mqttUser = parseJSONValue(body, "mqtt_user");
        String mqttPassword = parseJSONValue(body, "mqtt_password");
        
        int mqttPort = mqttPortStr.toInt();
        if (mqttPort == 0) mqttPort = 1883; // 默认端口
        
        Serial.print("Parsed - SSID: "); Serial.println(ssid);
        Serial.print("Password length: "); Serial.println(password.length());
        Serial.print("MQTT Server: "); Serial.println(mqttServer);
        Serial.print("MQTT Port: "); Serial.println(mqttPort);
        Serial.print("MQTT User: "); Serial.println(mqttUser);
        Serial.print("MQTT Password length: "); Serial.println(mqttPassword.length());
        
        if (ssid.length() > 0) {
            // 立即返回响应，避免客户端超时
            server.send(200, "application/json", "{\"status\":\"success\",\"message\":\"Config received, connecting to WiFi...\"}");
            
            // 保存WiFi凭证
            if (saveWiFiCredentials(ssid, password)) {
                Serial.println("WiFi credentials saved successfully");
                
                // 保存MQTT配置
                if (saveMQTTCredentials(mqttServer, mqttPort, mqttUser, mqttPassword)) {
                    Serial.println("MQTT configuration saved successfully");
                } else {
                    Serial.println("Failed to save MQTT configuration");
                }

                // 重置间隔配置为默认值（重新配网后重置）
                resetIntervalConfig();
                Serial.println("Interval configuration reset to defaults after reconfiguration");
                
                // 显示连接信息
                if (displayCallback) {
                    displayCallback("Connecting to", ssid, "Please wait...");
                }
                
                // 尝试连接到新WiFi
                if (connectToWiFi(ssid, password, 40)) {
                    Serial.println("WiFi connected successfully, preparing to restart device...");
                    
                    // 显示重启信息
                    if (displayCallback) {
                        displayCallback("WiFi Connected", "Device will", "restart in 3s...");
                    }
                    
                    // 延迟3秒后重启，让用户看到消息
                    delay(3000);
                    
                    Serial.println("Configuration completed, restarting device...");
                    ESP.restart();
                } else {
                    Serial.println("WiFi connection failed, keeping config mode");
                    if (displayCallback) {
                        displayCallback("Connect Failed", "Check WiFi Config", "Config Mode Active");
                    }
                }
            } else {
                Serial.println("Failed to save WiFi credentials, keeping config mode");
                if (displayCallback) {
                    displayCallback("Save Failed", "EEPROM Error", "Config Mode Active");
                }
            }
        } else {
            Serial.println("SSID is empty");
            server.send(400, "application/json", "{\"status\":\"error\",\"message\":\"SSID is required\"}");
        }
    } else {
        Serial.println("No configuration data received");
        server.send(400, "application/json", "{\"status\":\"error\",\"message\":\"No data received\"}");
    }
}

String WiFiManager::parseJSONValue(String json, String key) {
    String searchKey = "\"" + key + "\":\"";
    int start = json.indexOf(searchKey);
    if (start == -1) return "";
    
    start += searchKey.length();
    int end = json.indexOf("\"", start);
    if (end == -1) return "";
    
    return json.substring(start, end);
}

void WiFiManager::handleStatus() {
    String status = "connecting";
    String ip = "";
    
    if (WiFi.status() == WL_CONNECTED) {
        status = "connected";
        ip = WiFi.localIP().toString();
    }
    
    String json = "{\"status\":\"" + status + "\",\"ip\":\"" + ip + "\"}";
    server.send(200, "application/json", json);
}

void WiFiManager::handleNotFound() {
    server.send(404, "text/plain", "Not Found");
}

bool WiFiManager::saveWiFiCredentials(String ssid, String password) {
    Serial.println("Saving WiFi credentials to EEPROM...");
    
    if (!EEPROM.begin(EEPROM_SIZE)) {
        Serial.println("EEPROM initialization failed!");
        return false;
    }
    
    // 清空之前的数据
    for (int i = 0; i < 96; i++) {
        EEPROM.write(i, 0);
    }
    
    // 保存SSID
    for (int i = 0; i < ssid.length() && i < 31; i++) {
        EEPROM.write(SSID_ADDR + i, ssid[i]);
    }
    EEPROM.write(SSID_ADDR + ssid.length(), 0);
    
    // 保存密码
    for (int i = 0; i < password.length() && i < 63; i++) {
        EEPROM.write(PASS_ADDR + i, password[i]);
    }
    EEPROM.write(PASS_ADDR + password.length(), 0);
    
    // 提交到EEPROM
    bool success = EEPROM.commit();
    EEPROM.end();
    
    if (success) {
        Serial.println("WiFi credentials saved successfully");
        
        // 验证保存的数据
        String savedSSID, savedPassword;
        if (loadWiFiCredentials(savedSSID, savedPassword)) {
            Serial.print("Verified saved SSID: ");
            Serial.println(savedSSID);
            
            if (savedSSID == ssid && savedPassword == password) {
                Serial.println("WiFi credentials verification successful");
                return true;
            } else {
                Serial.println("WiFi credentials verification failed: saved data does not match original");
                return false;
            }
        } else {
            Serial.println("WiFi credentials verification failed: unable to read saved data");
            return false;
        }
    } else {
        Serial.println("Failed to save WiFi credentials: EEPROM commit failed");
        return false;
    }
}

bool WiFiManager::loadWiFiCredentials(String &ssid, String &password) {
    Serial.println("Loading WiFi credentials from EEPROM...");
    
    if (!EEPROM.begin(EEPROM_SIZE)) {
        Serial.println("EEPROM initialization failed!");
        return false;
    }
    
    ssid = "";
    char ch = EEPROM.read(SSID_ADDR);
    int addr = SSID_ADDR;
    while (addr < PASS_ADDR && ch != 0) {
        ssid += ch;
        addr++;
        ch = EEPROM.read(addr);
    }
    
    password = "";
    ch = EEPROM.read(PASS_ADDR);
    addr = PASS_ADDR;
    while (addr < PASS_ADDR + 64 && ch != 0) {
        password += ch;
        addr++;
        ch = EEPROM.read(addr);
    }
    
    EEPROM.end();
    
    if (ssid.length() > 0) {
        Serial.print("Loaded saved WiFi: ");
        Serial.println(ssid);
        return true;
    } else {
        Serial.println("No saved WiFi credentials found");
        return false;
    }
}

bool WiFiManager::connectToWiFi(String ssid, String password, int maxAttempts) {
    Serial.print("Connecting to WiFi: ");
    Serial.println(ssid);
    
    isConnecting = true;
    
    // 设置WiFi模式为STA
    WiFi.mode(WIFI_STA);
    
    // 清除之前的配置
    WiFi.disconnect();
    delay(100);
    
    // 开始连接
    WiFi.begin(ssid.c_str(), password.c_str());
    
    int attempts = 0;
    while (WiFi.status() != WL_CONNECTED && attempts < maxAttempts) {
        delay(1000);
        attempts++;
        Serial.print(".");
        
        // 每5次尝试显示一次进度
        if (attempts % 5 == 0) {
            Serial.print("Attempt ");
            Serial.print(attempts);
            Serial.print("/");
            Serial.println(maxAttempts);
        }
        
        // 在连接过程中处理服务器请求
        if (inConfigMode) {
            server.handleClient();
        }
    }
    
    if (WiFi.status() == WL_CONNECTED) {
        isConnected = true;
        isConnecting = false;
        Serial.println("");
        Serial.println("WiFi connected successfully!");
        Serial.print("IP address: ");
        Serial.println(WiFi.localIP());
        Serial.print("Signal strength: ");
        Serial.print(WiFi.RSSI());
        Serial.println(" dBm");
        return true;
    } else {
        Serial.println("");
        Serial.println("WiFi connection failed");
        Serial.print("Final WiFi status: ");
        Serial.println(WiFi.status());
        isConnecting = false;
        return false;
    }
}

bool WiFiManager::saveMQTTCredentials(String server, int port, String user, String password) {
    Serial.println("Saving MQTT configuration to EEPROM...");
    
    if (!EEPROM.begin(EEPROM_SIZE)) {
        Serial.println("EEPROM initialization failed!");
        return false;
    }
    
    // 调试：打印要保存的数据
    Serial.print("Saving MQTT server: "); Serial.println(server);
    Serial.print("Saving MQTT port: "); Serial.println(port);
    Serial.print("Saving MQTT user: "); Serial.println(user);
    Serial.print("Saving MQTT password length: "); Serial.println(password.length());
    
    // 清空MQTT配置区域
    for (int i = MQTT_SERVER_ADDR; i < MQTT_PASSWORD_ADDR + 64; i++) {
        EEPROM.write(i, 0);
    }
    
    // 保存MQTT服务器地址
    int addr = MQTT_SERVER_ADDR;
    for (int i = 0; i < server.length() && i < 31; i++) {
        EEPROM.write(addr++, server[i]);
    }
    EEPROM.write(addr, 0); // 字符串终止符
    
    // 保存MQTT端口
    EEPROM.write(MQTT_PORT_ADDR, (port >> 8) & 0xFF);
    EEPROM.write(MQTT_PORT_ADDR + 1, port & 0xFF);
    
    // 保存MQTT用户名
    addr = MQTT_USER_ADDR;
    for (int i = 0; i < user.length() && i < 31; i++) {
        EEPROM.write(addr++, user[i]);
    }
    EEPROM.write(addr, 0); // 字符串终止符
    
    // 保存MQTT密码
    addr = MQTT_PASSWORD_ADDR;
    for (int i = 0; i < password.length() && i < 63; i++) {
        EEPROM.write(addr++, password[i]);
    }
    EEPROM.write(addr, 0); // 字符串终止符
    
    // 提交到EEPROM
    bool success = EEPROM.commit();
    
    if (success) {
        Serial.println("MQTT configuration saved successfully, verifying...");
        
        // 立即验证保存的数据
        String verifyServer, verifyUser, verifyPassword;
        int verifyPort;
        
        // 重新读取验证
        verifyServer = "";
        for (int i = MQTT_SERVER_ADDR; i < MQTT_SERVER_ADDR + 32; i++) {
            char ch = EEPROM.read(i);
            if (ch == 0) break;
            verifyServer += ch;
        }
        
        uint8_t portHigh = EEPROM.read(MQTT_PORT_ADDR);
        uint8_t portLow = EEPROM.read(MQTT_PORT_ADDR + 1);
        verifyPort = (portHigh << 8) | portLow;
        
        verifyUser = "";
        for (int i = MQTT_USER_ADDR; i < MQTT_USER_ADDR + 32; i++) {
            char ch = EEPROM.read(i);
            if (ch == 0) break;
            verifyUser += ch;
        }
        
        verifyPassword = "";
        for (int i = MQTT_PASSWORD_ADDR; i < MQTT_PASSWORD_ADDR + 64; i++) {
            char ch = EEPROM.read(i);
            if (ch == 0) break;
            verifyPassword += ch;
        }
        
        Serial.print("Verify - server: "); Serial.println(verifyServer);
        Serial.print("Verify - port: "); Serial.println(verifyPort);
        Serial.print("Verify - user: "); Serial.println(verifyUser);
        Serial.print("Verify - password length: "); Serial.println(verifyPassword.length());
        
        // 检查验证结果
        if (verifyServer == server && verifyPort == port && 
            verifyUser == user && verifyPassword == password) {
            Serial.println("MQTT configuration verification successful!");
            success = true;
        } else {
            Serial.println("MQTT configuration verification failed!");
            success = false;
        }
    } else {
        Serial.println("Failed to save MQTT configuration: EEPROM commit failed");
    }
    
    EEPROM.end();
    return success;
}

bool WiFiManager::loadMQTTCredentials(String &server, int &port, String &user, String &password) {
    Serial.println("Loading MQTT configuration from EEPROM...");
    
    if (!EEPROM.begin(EEPROM_SIZE)) {
        Serial.println("EEPROM initialization failed!");
        return false;
    }
    
    // 读取MQTT服务器地址
    server = "";
    for (int i = MQTT_SERVER_ADDR; i < MQTT_SERVER_ADDR + 32; i++) {
        char ch = EEPROM.read(i);
        if (ch == 0) break;
        server += ch;
    }
    
    // 读取MQTT端口
    uint8_t portHigh = EEPROM.read(MQTT_PORT_ADDR);
    uint8_t portLow = EEPROM.read(MQTT_PORT_ADDR + 1);
    port = (portHigh << 8) | portLow;
    
    // 如果端口异常，使用默认值
    if (port == 0 || port == 65535) {
        port = 1883;
    }
    
    // 读取MQTT用户名
    user = "";
    for (int i = MQTT_USER_ADDR; i < MQTT_USER_ADDR + 32; i++) {
        char ch = EEPROM.read(i);
        if (ch == 0) break;
        user += ch;
    }
    
    // 读取MQTT密码
    password = "";
    for (int i = MQTT_PASSWORD_ADDR; i < MQTT_PASSWORD_ADDR + 64; i++) {
        char ch = EEPROM.read(i);
        if (ch == 0) break;
        password += ch;
    }
    
    EEPROM.end();
    
    // 验证读取的数据
    bool isValid = true;
    
    // 检查服务器地址是否有效（不能为空且不能全是乱码）
    if (server.length() == 0) {
        Serial.println("MQTT server address is empty");
        isValid = false;
    }
    
    // 检查端口是否在有效范围内
    if (port < 1 || port > 65535) {
        Serial.println("MQTT port is invalid");
        isValid = false;
    }
    
    // 检查字符串是否包含可打印字符
    for (int i = 0; i < server.length(); i++) {
        if (server[i] < 32 || server[i] > 126) {
            Serial.println("MQTT server address contains non-printable characters");
            isValid = false;
            break;
        }
    }
    
    if (isValid) {
        Serial.print("Loaded MQTT configuration - Server: "); Serial.println(server);
        Serial.print("Port: "); Serial.println(port);
        Serial.print("User: "); Serial.println(user.length() > 0 ? user : "None");
        Serial.print("Password length: "); Serial.println(password.length());
        return true;
    } else {
        Serial.println("Invalid MQTT configuration, using default configuration");
        return false;
    }
}

void WiFiManager::clearMQTTCredentials() {
    Serial.println("Clearing MQTT configuration...");
    if (!EEPROM.begin(EEPROM_SIZE)) {
        Serial.println("EEPROM initialization failed!");
        return;
    }
    
    // 清空MQTT配置区域
    for (int i = MQTT_SERVER_ADDR; i < MQTT_PASSWORD_ADDR + 64; i++) {
        EEPROM.write(i, 0);
    }
    
    if (!EEPROM.commit()) {
        Serial.println("EEPROM commit failed!");
    } else {
        Serial.println("MQTT configuration cleared");
    }
    
    EEPROM.end();
}

/**
 * @brief 处理WiFi网络扫描请求
 */
void WiFiManager::handleScan() {
    Serial.println("Starting WiFi scan...");
    
    // 添加CORS头
    server.sendHeader("Access-Control-Allow-Origin", "*");
    server.sendHeader("Access-Control-Allow-Methods", "GET,OPTIONS");
    server.sendHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    
    // 处理OPTIONS预检请求
    if (server.method() == HTTP_OPTIONS) {
        server.send(200, "text/plain", "");
        return;
    }
    
    // 设置WiFi模式为STA+AP以便扫描
    WiFi.mode(WIFI_AP_STA);
    delay(100);
    
    // 开始异步扫描
    int scanResult = WiFi.scanNetworks(true, true);
    
    if (scanResult == WIFI_SCAN_RUNNING) {
        Serial.println("WiFi scan started successfully");
        server.send(202, "application/json", "{\"status\":\"scanning\",\"message\":\"Scan in progress\"}");
    } else if (scanResult < 0) {
        Serial.println("WiFi scan failed to start");
        server.send(500, "application/json", "{\"status\":\"error\",\"message\":\"Scan failed to start\"}");
    }
}

/**
 * @brief 处理WiFi扫描结果请求
 */
void WiFiManager::handleScanResults() {
    Serial.println("Checking WiFi scan results...");
    
    // 添加CORS头
    server.sendHeader("Access-Control-Allow-Origin", "*");
    server.sendHeader("Access-Control-Allow-Methods", "GET,OPTIONS");
    server.sendHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    
    // 处理OPTIONS预检请求
    if (server.method() == HTTP_OPTIONS) {
        server.send(200, "text/plain", "");
        return;
    }
    
    int scanResult = WiFi.scanComplete();
    
    if (scanResult == WIFI_SCAN_RUNNING) {
        Serial.println("Scan still in progress");
        server.send(202, "application/json", "{\"status\":\"scanning\",\"message\":\"Scan still in progress\"}");
        return;
    } else if (scanResult < 0) {
        Serial.println("Scan failed or not started");
        server.send(500, "application/json", "{\"status\":\"error\",\"message\":\"Scan failed or not started\"}");
        return;
    }
    
    Serial.print("WiFi scan completed. Found ");
    Serial.print(scanResult);
    Serial.println(" networks");
    
    // 构建网络列表JSON
    String json = "{\"status\":\"completed\",\"networks\":[";
    int validNetworkCount = 0;
    
    for (int i = 0; i < scanResult; i++) {
        String ssid = WiFi.SSID(i);
        int rssi = WiFi.RSSI(i);
        
        // 过滤条件：SSID不为空且信号强度足够
        if (ssid.length() == 0 || rssi <= -95) {
            Serial.print("Skipping network: ");
            Serial.print(ssid);
            Serial.print(" (RSSI: ");
            Serial.print(rssi);
            Serial.println(")");
            continue;
        }
        
        // 处理隐藏网络
        if (ssid.length() == 0) {
            ssid = "[隐藏网络]";
        }
        
        // 限制SSID长度，防止过长
        if (ssid.length() > 32) {
            ssid = ssid.substring(0, 32) + "...";
        }
        
        if (validNetworkCount > 0) json += ",";
        json += "{";
        json += "\"ssid\":\"" + escapeJSONString(ssid) + "\",";
        json += "\"rssi\":" + String(rssi) + ",";
        json += "\"encryption\":" + String(WiFi.encryptionType(i)) + ",";
        json += "\"channel\":" + String(WiFi.channel(i)) + ",";
        json += "\"is_hidden\":" + String(ssid == "[隐藏网络]" ? "true" : "false");
        json += "}";
        
        validNetworkCount++;
        
        // 限制返回数量，避免内存问题
        if (validNetworkCount >= 20) break;
    }
    
    json += "],\"total_found\":" + String(scanResult) + ",\"valid_count\":" + String(validNetworkCount) + "}";
    
    server.send(200, "application/json", json);
    
    // 清理扫描结果
    WiFi.scanDelete();
    
    // 恢复为AP模式
    WiFi.mode(WIFI_AP);
    
    Serial.print("Returned ");
    Serial.print(validNetworkCount);
    Serial.println(" valid networks");
}

/**
 * @brief 转义JSON字符串中的特殊字符
 */
String WiFiManager::escapeJSONString(String input) {
    String output = "";
    for (int i = 0; i < input.length(); i++) {
        char c = input.charAt(i);
        switch (c) {
            case '"': output += "\\\""; break;
            case '\\': output += "\\\\"; break;
            case '\b': output += "\\b"; break;
            case '\f': output += "\\f"; break;
            case '\n': output += "\\n"; break;
            case '\r': output += "\\r"; break;
            case '\t': output += "\\t"; break;
            default: output += c; break;
        }
    }
    return output;
}

/**
 * @brief 保存间隔配置到EEPROM
 * @param sensorInterval 传感器采集间隔(ms)
 * @param publishInterval 数据发布间隔(ms)
 * @param displayInterval 显示更新间隔(ms)
 * @return true-保存成功, false-保存失败
 */
bool WiFiManager::saveIntervalConfig(unsigned long sensorInterval, unsigned long publishInterval, unsigned long displayInterval) {
    Serial.println("Saving interval configuration to EEPROM...");
    
    if (!EEPROM.begin(EEPROM_SIZE)) {
        Serial.println("EEPROM initialization failed!");
        return false;
    }
    
    // 保存传感器采集间隔 (4字节)
    EEPROM.write(SENSOR_INTERVAL_ADDR, (sensorInterval >> 24) & 0xFF);
    EEPROM.write(SENSOR_INTERVAL_ADDR + 1, (sensorInterval >> 16) & 0xFF);
    EEPROM.write(SENSOR_INTERVAL_ADDR + 2, (sensorInterval >> 8) & 0xFF);
    EEPROM.write(SENSOR_INTERVAL_ADDR + 3, sensorInterval & 0xFF);
    
    // 保存数据发布间隔 (4字节)
    EEPROM.write(PUBLISH_INTERVAL_ADDR, (publishInterval >> 24) & 0xFF);
    EEPROM.write(PUBLISH_INTERVAL_ADDR + 1, (publishInterval >> 16) & 0xFF);
    EEPROM.write(PUBLISH_INTERVAL_ADDR + 2, (publishInterval >> 8) & 0xFF);
    EEPROM.write(PUBLISH_INTERVAL_ADDR + 3, publishInterval & 0xFF);
    
    // 保存显示更新间隔 (4字节)
    EEPROM.write(DISPLAY_INTERVAL_ADDR, (displayInterval >> 24) & 0xFF);
    EEPROM.write(DISPLAY_INTERVAL_ADDR + 1, (displayInterval >> 16) & 0xFF);
    EEPROM.write(DISPLAY_INTERVAL_ADDR + 2, (displayInterval >> 8) & 0xFF);
    EEPROM.write(DISPLAY_INTERVAL_ADDR + 3, displayInterval & 0xFF);
    
    bool success = EEPROM.commit();
    EEPROM.end();
    
    if (success) {
        Serial.println("Interval configuration saved successfully");
        Serial.print("Sensor interval: "); Serial.println(sensorInterval);
        Serial.print("Publish interval: "); Serial.println(publishInterval);
        Serial.print("Display interval: "); Serial.println(displayInterval);
    } else {
        Serial.println("Failed to save interval configuration: EEPROM commit failed");
    }
    
    return success;
}

/**
 * @brief 从EEPROM加载间隔配置
 * @param sensorInterval 传感器采集间隔(ms)
 * @param publishInterval 数据发布间隔(ms)
 * @param displayInterval 显示更新间隔(ms)
 * @return true-加载成功, false-加载失败(使用默认值)
 */
bool WiFiManager::loadIntervalConfig(unsigned long &sensorInterval, unsigned long &publishInterval, unsigned long &displayInterval) {
    Serial.println("Loading interval configuration from EEPROM...");
    
    if (!EEPROM.begin(EEPROM_SIZE)) {
        Serial.println("EEPROM initialization failed!");
        return false;
    }
    
    // 读取传感器采集间隔
    uint32_t sensorInt = 0;
    sensorInt |= (uint32_t)EEPROM.read(SENSOR_INTERVAL_ADDR) << 24;
    sensorInt |= (uint32_t)EEPROM.read(SENSOR_INTERVAL_ADDR + 1) << 16;
    sensorInt |= (uint32_t)EEPROM.read(SENSOR_INTERVAL_ADDR + 2) << 8;
    sensorInt |= EEPROM.read(SENSOR_INTERVAL_ADDR + 3);
    
    // 读取数据发布间隔
    uint32_t publishInt = 0;
    publishInt |= (uint32_t)EEPROM.read(PUBLISH_INTERVAL_ADDR) << 24;
    publishInt |= (uint32_t)EEPROM.read(PUBLISH_INTERVAL_ADDR + 1) << 16;
    publishInt |= (uint32_t)EEPROM.read(PUBLISH_INTERVAL_ADDR + 2) << 8;
    publishInt |= EEPROM.read(PUBLISH_INTERVAL_ADDR + 3);
    
    // 读取显示更新间隔
    uint32_t displayInt = 0;
    displayInt |= (uint32_t)EEPROM.read(DISPLAY_INTERVAL_ADDR) << 24;
    displayInt |= (uint32_t)EEPROM.read(DISPLAY_INTERVAL_ADDR + 1) << 16;
    displayInt |= (uint32_t)EEPROM.read(DISPLAY_INTERVAL_ADDR + 2) << 8;
    displayInt |= EEPROM.read(DISPLAY_INTERVAL_ADDR + 3);
    
    EEPROM.end();
    
    // 验证读取的值是否有效
    bool isValid = true;
    
    // 传感器间隔验证 (100ms - 3600000ms)
    if (sensorInt < 100 || sensorInt > 3600000) {
        Serial.println("Invalid sensor interval in EEPROM");
        isValid = false;
    } else {
        sensorInterval = sensorInt;
    }
    
    // 发布间隔验证 (100ms - 3600000ms)
    if (publishInt < 100 || publishInt > 3600000) {
        Serial.println("Invalid publish interval in EEPROM");
        isValid = false;
    } else {
        publishInterval = publishInt;
    }
    
    // 显示间隔验证 (100ms - 60000ms)
    if (displayInt < 100 || displayInt > 60000) {
        Serial.println("Invalid display interval in EEPROM");
        isValid = false;
    } else {
        displayInterval = displayInt;
    }
    
    if (isValid) {
        Serial.print("Loaded interval configuration - Sensor: ");
        Serial.print(sensorInterval);
        Serial.print("ms, Publish: ");
        Serial.print(publishInterval);
        Serial.print("ms, Display: ");
        Serial.print(displayInterval);
        Serial.println("ms");
        return true;
    } else {
        Serial.println("Invalid interval configuration, using defaults");
        return false;
    }
}

/**
 * @brief 重置间隔配置为默认值
 */
void WiFiManager::resetIntervalConfig() {
    Serial.println("Resetting interval configuration to defaults");
    
    // 默认值
    unsigned long defaultSensorInterval = 500;    // 500ms
    unsigned long defaultPublishInterval = 1000;  // 1000ms
    unsigned long defaultDisplayInterval = 1000;  // 1000ms
    
    saveIntervalConfig(defaultSensorInterval, defaultPublishInterval, defaultDisplayInterval);
}

/**
 * @brief 清除间隔配置
 */
void WiFiManager::clearIntervalConfig() {
    Serial.println("Clearing interval configuration...");
    
    if (!EEPROM.begin(EEPROM_SIZE)) {
        Serial.println("EEPROM initialization failed!");
        return;
    }
    
    // 清除间隔配置区域
    for (int i = SENSOR_INTERVAL_ADDR; i <= DISPLAY_INTERVAL_ADDR + 3; i++) {
        EEPROM.write(i, 0);
    }
    
    if (!EEPROM.commit()) {
        Serial.println("EEPROM commit failed!");
    } else {
        Serial.println("Interval configuration cleared");
    }
    
    EEPROM.end();
}